package samples;

import hermesV2.Message;
import hermesV2.PlaceAddress;
import hermesV2.agent.CloneException;
import hermesV2.agent.CommunicationException;
import hermesV2.agent.Identificator;
import hermesV2.agent.InteractionContainer;
import hermesV2.agent.MigrationException;
import hermesV2.agent.UserAgent;
import hermesV2.services.P2P_ServiceAgent;

import java.util.Date;
import java.util.Vector;


public class McDuckAgent extends UserAgent {

  /**
	 * 
	 */
	private static final long serialVersionUID = -4352463150315587259L;
	private Vector<PlaceAddress> peers;


public McDuckAgent(String agentName) {
    super("Della Duck");
  }

  public void init() {
    reception(); //I enable the reception
                 //of messages for the father
    peers = getPeersList();
   System.out.println(" Hello I'm Della Duck !!!");

    Identificator temp=null,son1=null,son2=null,son3=null;

    /*afterCloning is the first method
      called after the clonation*/

    try {
      son1 = clone("afterCloning", "Qui");
     System.out.println(new Date(System.currentTimeMillis()) +": Qui was born !!");
      son2 = clone("afterCloning", "Quo");
     System.out.println(new Date(System.currentTimeMillis()) +": Quo was born !!");
      son3 = clone("afterCloning", "Qua");
     System.out.println(new Date(System.currentTimeMillis()) +": Qua was born !!");
    } catch (CloneException ce) {System.out.println( "Error "+ce); }
    Message<?> m0=null,m1=null,m2=null,m3=null;
    while (m1==null || m2==null || m3==null){
        m0 = getMessageSynch();
        temp = m0.getSenderAgentId();
        if (son1.equals(temp)) m1 = m0;
        if (son2.equals(temp)) m2 = m0;
        if (son3.equals(temp)) m3 = m0;
       System.out.println((String)m0.getObject());
    }
    
    /*The mother replies to sons*/
    Identificator myId = getIdentificator();
    m1 = new Message<String>(myId,  m1.getSenderAgentId(),
                "Mom: Ok Qui !! \n     "+
                "I've receive your message.");
    m2 = new Message<String>(myId, m2.getSenderAgentId(),
                "Mom: Ok Quo !! \n     "+
                "I've receive your message.");
    m3 = new Message<String>(myId, m3.getSenderAgentId(),
                "Mom: Ok Qua !! \n     "+
                "I've receive your message.");
    try {
      sendMessageToUserAgent(m1);
      sendMessageToUserAgent(m2);
      sendMessageToUserAgent(m3);
    } catch (CommunicationException ce) {
      System.out.println(ce.getMessage());
    }
  }
  public void afterCloning() {
    try {
      // the service p2p is required!
      Identificator requiredServiceId = basicServices.getDiscoveryServiceAgentInterface().getServiceId("PeerToPeer_v1.0");
      if ( null == requiredServiceId)
      		{
    	 System.out.println("the Service Agent P2P is required but not found!!");
    	     return; // terminate the user agent.
      		}
      
      PlaceAddress  newMPA = new PlaceAddress(peers.get(0).getIp(), peers.get(0).getPort(), peers.get(0).getPhoneNumber());      
      this.move(newMPA, "afterMoving");
    } catch (MigrationException me) {
    	me.printStackTrace();
    	System.out.println("MigrationException" + me);
    }
  }

  public void afterMoving() {
    reception(); //I enable the reception
                 //of messages for the son

    Identificator myId = getIdentificator();
    Identificator mother = getFatherIdentificator();
    Message<?> m = null;

    try {
        m = new Message<String>(myId, mother,
              getAgentName() +
              ": I have moved to another Place");
        sendMessageToUserAgent(m);
    } catch (CommunicationException ce) {
    	System.out.println(ce.getMessage());
    }
    m = getMessageSynch();
    System.out.println((String)m.getObject());
    this.dead();
    
    /*try {

        PlaceAddress  myMPA =
                new PlaceAddress("193.204.13.100", 8000);
        
        //193.204.13.100
        this.move(myMPA, "afterMovingAgain");
      } catch (MigrationException me) {
      	me.printStackTrace();
        System.out.println("MigrationException" + me);
      }*/
 }
  
  /*public void afterMovingAgain() {
	 System.out.println("Hello World !!");  
	  
	  
  }*/
  
  
  private Vector<PlaceAddress> getPeersList()
  {
   loginToService(getServiceIdentificator("PeerToPeer_v1.0"), "ezio", "ezio");
   Identificator serviceId = getServiceIdentificator("PeerToPeer_v1.0");
   InteractionContainer ic = new InteractionContainer(getServiceProtocol(serviceId));
   ic.makeInteraction("AskPeersList", "");
   try {
	sendMessageToServiceAgent(new Message<InteractionContainer>(getIdentificator(), serviceId, ic));
       } 
   catch (CommunicationException e) {System.out.println( "Error "+e);
}
   Message<?> response = getMessageSynch();
   Vector<PlaceAddress> resultList=  (Vector<PlaceAddress>) ((InteractionContainer)response.getObject()).getParameter("PeersList");
   return resultList;
    
  }

  


  
}

